package jp.co.itfrontier.mashup.command
{
	import jp.co.itfrontier.mashup.event.IEvent;
	import jp.co.itfrontier.mashup.core.ModelLocater;
	import jp.co.itfrontier.mashup.vo.BookVO;
	import jp.co.itfrontier.mashup.core.Logger;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.events.Event;
	import jp.co.itfrontier.mashup.core.EventController;
	import flash.net.URLVariables;
	import jp.co.itfrontier.mashup.event.ChangeModelEvent;
	import jp.co.itfrontier.mashup.vo.ReviewVO;
	import mx.controls.sliderClasses.SliderLabel;
	import mx.managers.PopUpManager;
	import mx.core.Application;
	import flash.display.Sprite;

	public class AmazonBookSearch {

		private const url:String = "http://ecs.amazonaws.jp/onca/xml";
//		private const SubscriptionId:String = "0525E2PQ81DD7ZTWTK82";
		private const AWSAccessKeyId:String = "1ZZQW1D0FQEWK2T5FZ02";
//		private const ResponseGroup:String = "Large,Images";
		private const SearchIndex:String = "Books";
		private const Sort:String = "salesrank";
		private const Service:String = "AWSECommerceService";
		private const Operation:String = "ItemSearch";
		private const ItemPage:int = 1; //取ってくるページの指定

		// 指定URLリクエストからデータを取得するクラス
		private var urlLoader:URLLoader;

		[ArrayElementType(type="flash.net.URLRequest")]
		private var params:Array;

		[ArrayElementType(type="SlideString")]
		private var ss:Array;

		public function AmazonBookSearch() {
			urlLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, responseCompleteHandler);
			ss = new Array();
		}

		public function searchBooks(keys:Array):void{

			params = new Array();

			ModelLocater.getInstance().books = new Array();

			for each (var key:String in keys) {
				//探してみます
				var urlVar:URLVariables = new URLVariables();

				//urlVar.SubscriptionId = SubscriptionId;
				urlVar.AWSAccessKeyId = AWSAccessKeyId;
				urlVar.ResponseGroup = ResponseGroup;
				urlVar.SearchIndex = SearchIndex;
				urlVar.Sort = Sort;
				urlVar.Service = Service;
				urlVar.Operation = Operation;
				urlVar.Keywords = key;
				urlVar.ItemPage = ItemPage;//取ってくるページの指定

				var urlRequest:URLRequest = new URLRequest();
				urlRequest.url = url;
				urlRequest.data = urlVar;

				params.push(urlRequest);

			}

			params = params.reverse();

			loopLoader(params.pop());

		}

		private function loopLoader(req:URLRequest):void {
			urlLoader.load(req);
			Logger.getInstance().info("amazon::execute 残り" + params.length);
		}


		private const ResponseGroup:String = "Images,Reviews,ItemAttributes,ItemIds";

		private function responseCompleteHandler(event:Event):void {

			var resultXML:XML = new XML(urlLoader.data);
			var amazon:Namespace = new Namespace("http://webservices.amazon.com/AWSECommerceService/2005-10-05");
 			var result:Array = new Array();
			var keyword:String = resultXML..amazon::Request.amazon::ItemSearchRequest.amazon::Keywords;
			var pagecount:int = resultXML..amazon::TotalPages;

			if ((resultXML..amazon::Item as XMLList) != null) {
				var s:SlideString = new SlideString();
				s.label = keyword;

				var a:Application = Application.application as Application;

				PopUpManager.addPopUp(s, a as Sprite);

				s.x = Math.random() * a.stage.width / 2 + 100;
				s.y = Math.random() * a.stage.height / 2 + 100;

				PopUpManager.removePopUp(ss.pop());

				ss.push(s);
			}

			//Amazonは10件しか帰ってきません。
			for each(var xml:XML in resultXML..amazon::Item) {

				var bvo:BookVO = new BookVO();

				// 一般情報
				bvo.asin = xml.amazon::ASIN;
				bvo.link = xml.amazon::DetailPageURL;
				bvo.salesRank = xml.amazon::salesRank;
				bvo.imageURL = xml.amazon::LargeImage.amazon::URL;

				// 著作情報
				var att:XML = xml.amazon::ItemAttributes[0];
				bvo.author = att..amazon::Author[0];
				bvo.isbn = att.amazon::ISBN;
				bvo.title = att.amazon::Title;
				bvo.word = keyword;
				bvo.prise = att..amazon::Amount;
				bvo.pageMax = att.amazon::NumberOfPages
				bvo.publisher = att.amazon::Publisher;
				bvo.publishData = att.amazon::PublicationDate;

				// 個別
				bvo.rating = xml..amazon::AverageRating;

				bvo.reviews = new Array();

				for each (var x:XML in xml..amazon::Review) {
					var r:ReviewVO = new ReviewVO();

					r.rait = x.amazon::Rating;
					r.summary = x.amazon::Summary;
					r.content = x.amazon::Content;

					bvo.reviews.push(r);
				}

				result.push(bvo);
				Logger.getInstance().info("AMAZON:" + bvo.title);
			}

			ModelLocater.getInstance().books = ModelLocater.getInstance().books.concat(result);

			if (params.length > 0) {
				loopLoader(params.pop());
			} else {
				Logger.getInstance().info("変更イベント");

				var len:Number = ss.length;
				for (var i:Number = 0; i < len; i++) {
					var _s:SlideString = ss[i];
					//_s.setVisible(false);
					PopUpManager.removePopUp(_s);
				}

				EventController.getInstance().dispatchEvent(new ChangeModelEvent(ChangeModelEvent.AMAZON));
			}
		}
	}
}